<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          content="创建新合同"
          @back="goBack"
        >
        </el-page-header>
        <div class="card-box--downloadbtn">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </div>
    </el-card>

    <el-card
      class="card-box form-box"
      :class="formData.projectTmpId ? '' : 'form-h'"
    >
      <template #header>
        <div class="card-box-header" @click="showBase = !showBase">
          <span>合同基础信息</span>
          <div v-if="showBase" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="showBase" class="content-box">
          <el-form
            :model="formData"
            class="content-box"
            :rules="rules"
            ref="formDataRef"
            label-width="180px"
          >
            <el-row :gutter="40">
              <el-col :xl="6" :lg="8">
                <el-form-item
                  label="合同名称"
                  prop="sectionName"
                  style="width: 312px"
                >
                  <el-select
                    v-model="formData.sectionName"
                    filterable
                    clearable
                    remote
                    placeholder="请输入合同名称"
                    :remote-method="
                      val => getContractCode(val, 'contractNameLike')
                    "
                    style="width: 171px"
                    allow-create
                    :disabled="sectionId ? true : false"
                    @change="changeContract('contractName')"
                  >
                    <el-option
                      class="default-option"
                      v-for="item in contractList"
                      :key="item.contractName"
                      :label="item.contractName"
                      :value="item.contractName"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xl="6" :lg="8">
                <el-form-item
                  label="合同编号"
                  prop="sectionCode"
                  style="width: 312px"
                >
                  <el-select
                    v-model="formData.sectionCode"
                    filterable
                    clearable
                    remote
                    placeholder="请输入合同编号"
                    :remote-method="
                      val => getContractCode(val, 'contractNoLike')
                    "
                    style="width: 171px"
                    allow-create
                    :disabled="sectionId ? true : false"
                    @change="changeContract('contractNo')"
                  >
                    <el-option
                      class="default-option"
                      v-for="item in contractList"
                      :key="item.contractNo"
                      :label="item.contractNo"
                      :value="item.contractNo"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40">
              <el-col :span="8">
                <el-form-item
                  label="合同类型"
                  prop="sectionType"
                  class="radio-item"
                >
                  <el-radio-group
                    v-model="formData.sectionType"
                    :disabled="true"
                    @change="selectRadio"
                    v-if="projectType === 'B1'"
                  >
                    <el-radio-button label="1">土建</el-radio-button>
                  </el-radio-group>
                  <el-radio-group
                    v-else
                    v-model="formData.sectionType"
                    :disabled="sectionId && formData.sectionType ? true : false"
                    @change="selectRadio"
                    style="display: flex; width: 172px"
                  >
                    <el-radio-button label="1">土建</el-radio-button>
                    <el-radio-button label="2">设备</el-radio-button>
                    <el-radio-button label="4">服务</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40" v-if="formData.sectionType == 1">
              <el-col :xl="6" :lg="8">
                <el-form-item label="安全文明任务" prop="projectTypeModel">
                  <div class="m-4 flex-item">
                    <el-cascader
                      v-model="formData.projectTypeModel"
                      :show-all-levels="false"
                      @change="handleChange"
                      :options="engineeringList"
                      :props="props2"
                      ref="cascader"
                      collapse-tags
                      collapse-tags-tooltip
                      :disabled="['1', '2'].includes(formData.startWorkStatus)"
                      clearable
                      style="width: 100%"
                    />
                    <p class="ml10">
                      已选择
                      <span class="red">{{
                        formData.projectTypeModel?.length
                      }}</span
                      >项
                    </p>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40" v-if="formData.sectionType == 2">
              <el-col :xl="6" :lg="8">
                <el-form-item label="项目模板" prop="projectTmpId">
                  <el-select
                    v-model="formData.projectTmpId"
                    value-key="id"
                    @change="handleChangeTemp"
                    style="width: 171px"
                    clearable
                    :disabled="
                      sectionId && formData.projectTmpId
                        ? true
                        : ['1', '2'].includes(formData.startWorkStatus)
                        ? true
                        : false
                    "
                  >
                    <el-option
                      class="default-option"
                      v-for="item in templateList"
                      :label="item.projectTemplateName"
                      :key="item.id"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="40" v-if="formData.sectionType == 4"> </el-row>

            <div v-if="show">
              <el-row style="margin-top: 1px">
                <el-col :xl="6" :lg="8">
                  <el-form-item label="项目负责人" prop="leaderInfo">
                    <el-select
                      v-model="formData.leaderInfo"
                      filterable
                      clearable
                      remote
                      placeholder="请输入姓名"
                      :remote-method="getUserData"
                      value-key="value"
                      style="width: 171px"
                      :disabled="['1', '2'].includes(formData.startWorkStatus)"
                    >
                      <el-option
                        class="default-option"
                        v-for="item in userList"
                        :key="item.value"
                        :label="item.label"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="isNotProjectA">
                <el-col :xl="6" :lg="8">
                  <el-form-item label="工期（天）" prop="durationCount">
                    <el-input-number
                      v-model="formData.durationCount"
                      :min="0"
                      :controls="false"
                      style="width: 171px"
                      placeholder="请输入工期"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="合同批准日期" prop="approvalTime">
                    <el-date-picker
                      v-model="formData.approvalTime"
                      type="date"
                      placeholder="请选择日期"
                      style="width: 171px"
                      value-format="YYYY-MM-DD"
                      clearable
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8" v-if="isNotProjectA">
                  <el-form-item label="合同签订日期" prop="signDate">
                    <el-date-picker
                      v-model="formData.signDate"
                      type="date"
                      placeholder="请选择日期"
                      style="width: 171px"
                      value-format="YYYY-MM-DD"
                      clearable
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xl="6" :lg="8">
                  <el-form-item
                    label="合同金额（含税，元）"
                    prop="contractAmount"
                  >
                    <el-input-number
                      v-model="formData.contractAmount"
                      :controls="false"
                      :min="-999999999.99"
                      :max="999999999.99"
                      precision="2"
                      style="width: 171px"
                      placeholder="请输入金额"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8">
                  <el-form-item
                    label="合同金额（不含税，元）"
                    prop="currencyAmountNoTax"
                  >
                    <el-input-number
                      v-model="formData.currencyAmountNoTax"
                      :controls="false"
                      :min="-999999999.99"
                      :max="999999999.99"
                      precision="2"
                      style="width: 171px"
                      placeholder="请输入金额"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同文书" prop="uploadFile">
                    <ecm-upload
                      :files="defaultFileList"
                      :disabled="true"
                      :hideText="true"
                    ></ecm-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <el-row :gutter="40" v-if="show">
              <el-col :xl="6" :lg="8">
                <span
                  style="margin-left: 44px; font-size: 14px; margin-top: 50px"
                  >合同详细信息</span
                >
                <div
                  class="sectionDetail"
                  style="
                    width: 830px;
                    overflow-x: scroll;
                    height: 350px;
                    border-style: ridge;
                    border-width: 0.8px;
                    margin-left: 140px;
                    margin-top: -15px;
                  "
                >
                  <el-row>
                    <el-col :span="5">
                      <div class="label" style="font-size: 14px">
                        合同采购方式
                      </div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        {{ contractInfo.purchaseContractClass }}
                      </div>
                    </el-col>
                    <el-col :span="5">
                      <div class="label">合同期限类型</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        {{ contractInfo.contractPeriodType }}
                      </div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="5">
                      <div class="label">合同起草日期</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        {{ contractInfo.contractCreateTime }}
                      </div>
                    </el-col>
                    <el-col :span="5">
                      <div class="label">合同起草部门</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">{{ contractInfo.companyName }}</div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="5">
                      <div class="label">合同模板分类</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">{{ contractInfo.templateName }}</div>
                    </el-col>
                    <el-col :span="5">
                      <div class="label">合同业务类别</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        {{ contractInfo.contractBusinessClassification }}
                      </div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="5">
                      <div class="label">原合同金额（含税，元）</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        {{ contractInfo.currencyAmount }}
                      </div>
                    </el-col>
                    <el-col :span="5">
                      <div class="label">原合同金额（不含税，元）</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        {{ contractInfo.currencyAmountNoTax }}
                      </div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="5">
                      <div class="label">合同相关方单位名称</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        <span
                          v-for="(item, index) in contractInfo.contractParties"
                          :key="index"
                          >{{ item.companyName
                          }}<i
                            v-if="
                              index != contractInfo.contractParties.length - 1
                            "
                            >、</i
                          ></span
                        >
                      </div>
                    </el-col>
                    <el-col :span="5">
                      <div class="label">合同相关方统一信用代码</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        <span
                          v-for="(item, index) in contractInfo.contractParties"
                          :key="index"
                          >{{ item.identityNo
                          }}<i
                            v-if="
                              index != contractInfo.contractParties.length - 1
                            "
                            >、</i
                          ></span
                        >
                      </div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="5">
                      <div class="label">合同相关方经办人</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        <span
                          v-for="(item, index) in contractInfo.contractParties"
                          :key="index"
                          >{{ item.linkmanName
                          }}<i
                            v-if="
                              index != contractInfo.contractParties.length - 1
                            "
                            >、</i
                          ></span
                        >
                      </div>
                    </el-col>
                    <el-col :span="5">
                      <div class="label">合同经办人联系方式</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        <span
                          v-for="(item, index) in contractInfo.contractParties"
                          :key="index"
                          >{{ item.linkmanMobile
                          }}<i
                            v-if="
                              index != contractInfo.contractParties.length - 1
                            "
                            >、</i
                          ></span
                        >
                      </div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="5">
                      <div class="label">合同签署件名称</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">{{ contractInfo.contractName }}</div>
                    </el-col>
                    <el-col :span="5">
                      <div class="label">供应商/承包商</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">{{ contractInfo.supplier }}</div>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="5">
                      <div class="label">合同附件</div>
                    </el-col>
                    <el-col :span="7">
                      <div class="value">
                        <span
                          v-for="(item, index) in contractInfo.contractFilelist"
                          :key="index"
                          >{{ item.fileName }}</span
                        >
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>

            <div v-else>
              <el-row style="margin-top: 1px">
                <el-col :xl="6" :lg="8">
                  <el-form-item label="项目负责人" prop="leaderInfo">
                    <el-select
                      v-model="formData.leaderInfo"
                      filterable
                      clearable
                      remote
                      placeholder="请输入姓名"
                      :remote-method="getUserData"
                      value-key="value"
                      style="width: 171px"
                    >
                      <el-option
                        class="default-option"
                        v-for="item in userList"
                        :key="item.value"
                        :label="item.label"
                        :value="item"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xl="6" :lg="8">
                  <el-form-item
                    label="合同金额（含税，元）"
                    prop="contractAmount"
                  >
                    <el-input-number
                      v-model="formData.contractAmount"
                      :min="-999999999.99"
                      :max="999999999.99"
                      precision="2"
                      :controls="false"
                      style="width: 171px"
                      placeholder="请输入金额"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8">
                  <el-form-item
                    label="合同金额（不含税，元）"
                    prop="currencyAmountNoTax"
                  >
                    <el-input-number
                      v-model="formData.currencyAmountNoTax"
                      :min="-999999999.99"
                      :max="999999999.99"
                      precision="2"
                      :controls="false"
                      style="width: 171px"
                      placeholder="请输入金额"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="isNotProjectA">
                <el-col :xl="6" :lg="8">
                  <el-form-item label="工期（天）" prop="durationCount">
                    <el-input-number
                      v-model="formData.durationCount"
                      :min="0"
                      :controls="false"
                      style="width: 171px"
                      placeholder="请输入工期"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="合同批准日期" prop="approvalTime">
                    <el-date-picker
                      v-model="formData.approvalTime"
                      type="date"
                      placeholder="请选择日期"
                      style="width: 171px"
                      value-format="YYYY-MM-DD"
                      clearable
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :xl="6" :lg="8" v-if="isNotProjectA">
                  <el-form-item label="合同签订日期" prop="signDate">
                    <el-date-picker
                      v-model="formData.signDate"
                      type="date"
                      placeholder="请选择日期"
                      style="width: 171px"
                      value-format="YYYY-MM-DD"
                      clearable
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xl="6" :lg="8">
                  <el-form-item
                    label="合同发起单位"
                    prop="sectionStartRegionCode"
                  >
                    <el-input
                      v-model.trim="filterText"
                      style="width: 171px"
                      placeholder="请选择"
                      @click.stop="handleDeptList(true)"
                    ></el-input>
                    <el-tree
                      clearable
                      style="width: 380px; border-width: 1px"
                      ref="treeRef"
                      class="filter-tree"
                      :data="deptList"
                      :props="defaultProps"
                      default-expand-all
                      :filter-node-method="filterNode"
                      v-if="showDeptList"
                      @node-click="handleChangeDept"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="isNotProjectA">
                <el-col :xl="6" :lg="8">
                  <el-form-item label="供应商/承包商" prop="supplier">
                    <el-input
                      v-model="formData.supplier"
                      placeholder="请输入供应商/承包商"
                      style="width: 171px"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xl="6" :lg="8">
                  <el-form-item label="项目年度" prop="projectYear">
                    <el-date-picker
                      v-model="formData.projectYear"
                      type="year"
                      placeholder="请选择年度"
                      style="width: 171px"
                      value-format="YYYY"
                      clearable
                      disabled
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同文书" prop="uploadFile">
                    <ecm-upload
                      :files="defaultFileList"
                      :formatRestriction="['pdf']"
                      @set-file="uploadFielChange"
                    ></ecm-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <el-card
      class="card-box"
      v-if="formData.projectTmpId && formData.sectionType == 2"
    >
      <template #header>
        <div class="card-box-header" @click="showTemplate = !showTemplate">
          <span>项目模版配置</span>
          <div v-if="showTemplate" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="showTemplate" class="content-box">
          <status-task-edit
            ref="editRef"
            :mode="isEdit ? 'edit' : 'read'"
            :templateId="templateId"
            :data="proStageList"
            :checkbox="true"
          ></status-task-edit>
        </div>
      </el-collapse-transition>
    </el-card>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  reactive,
  toRefs,
  watch,
  computed,
  nextTick
} from "vue";
import { useRoute, useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import StatusTaskEdit from "/@/views/projects/components/template/index.vue";
import { getUserList } from "/@/api/user";
import { getContractList } from "/@/api/user";
import { postDictList } from "/@/api/home";
import {
  addSection,
  updateSection,
  getSectionInfo,
  getContractBook,
  getBaseTree,
  projectTemplateList,
  getTemplateInfo,
  importSectionCode,
  getDeptTree,
  proSecContractFileList
} from "/@/api/projects";
import { storageLocal } from "/@/utils/storage";
import { clickEvent } from "/@/utils/func";
import EcmUpload from "/@/components/ecmUpload/index.vue";
export default defineComponent({
  components: { StatusTaskEdit, EcmUpload },
  props: {
    menuType: {
      type: String,
      default: "projectsA"
    }
  },
  setup(props) {
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const cascader = ref<HTMLFormElement | null>(null) as any;
    const editRef = ref<HTMLFormElement | null>(null) as any;
    const route = useRoute();
    const router = useRouter();
    const show = ref<boolean>(false);
    const projectInfo = storageLocal.getItem("projectInfo");
    const userList = ref([]);
    const contractList = ref([]);
    const templateList = ref([]);
    const isSearching = ref(false);
    const treeRef = ref<HTMLFormElement | null>(null) as any;
    let defaultFileList = ref([]) as any;

    const sectionId = route.query?.id || "";
    let isEdit = false;
    const filterNode = (value: string, data) => {
      if (!value) return true;
      return data.deptDescShrt.includes(value);
    };
    let deptList = ref([]);
    let expenseTypeList = ref([]);
    let templateId = ref();
    let proStageList = ref([]);
    let contractTypeList = [
      { dicValue: "A类合同", dicCode: "A" },
      { dicValue: "B类设备合同", dicCode: "B" }
    ];
    let state = reactive({
      formData: {
        // procureNum: "",
        sectionCode: "",
        sectionName: "",
        sectionType: projectInfo?.typeCode === "B1" ? "1" : "",
        projectId: projectInfo?.id,
        projectName: projectInfo?.name,
        leaderInfo: "" as any,
        leaderName: "",
        leaderId: "",
        contractNum: "" as any,
        projectTypeModel: [] as any,
        secEngineerList: [],
        projectTmpId: null as any,
        sectionStart: "",
        contractAmount: undefined,
        currencyAmountNoTax: undefined,
        durationCount: undefined,
        approvalTime: "",
        effectiveDate: "",
        signDate: "",
        projectYear: projectInfo?.projectYear,
        typeName: "" as any,
        sectionStartRegionCode: "",
        sectionStartRegionName: "",
        sectionStartFactoryCode: "",
        sectionStartFactoryName: "",
        supplier: "",
        expensesTypeCode: "",
        expensesTypeName: "",
        contractInfoId: "",
        contractId: "",
        sectionInfo: "" as any,
        startWorkStatus: ""
      },
      contractInfo: {
        contractNo: "",
        purchaseContractClass: "",
        contractPeriodType: "",
        contractCreateTime: "",
        createTime: "",
        companyName: "",
        // 关联评标报告
        // 关联标段（包）
        templateName: "",
        contractBusinessClassification: "",
        currencyAmount: "",
        currencyAmountNoTax: "",
        contractParties: [] as any,
        contractName: "",
        contractFilelist: [] as any,
        supplier: ""
      },
      engineerTypeArray: [],
      ext1Array: [],
      fbTypeArray: [],
      zfbTypeArray: [],
      fxTypeArray: [],
      engineeringList: [],
      props2: {
        multiple: true,
        value: "id",
        label: "itemText",
        emitPath: false //只返回改节点的值
      },
      showBase: true,
      showTemplate: true,
      projectType: projectInfo?.typeCode,
      defaultProps: {
        children: "children",
        label: "deptDescShrt"
      },
      showDeptList: false
    });

    const rules = {
      // procureNum: [
      //   { required: true, message: "请输入招标/采购编号", trigger: "blur" }
      // ],
      sectionCode: [
        { required: true, message: "请输入合同编号", trigger: "blur" }
      ],
      sectionName: [
        { required: true, message: "请输入合同名称", trigger: "blur" }
      ],
      sectionType: [
        { required: true, message: "请选择合同类型", trigger: "change" }
      ],
      leaderInfo: [
        { required: true, message: "请填写项目项目负责人", trigger: "change" }
      ],
      contractNum: [
        { required: true, message: "请选择标段合同", trigger: "change" }
      ],
      projectTypeModel: [
        { required: true, message: "请选择安全文明任务", trigger: "change" }
      ],
      projectTmpId: [
        { required: true, message: "请选择项目模板", trigger: "change" }
      ],
      contractAmount: [
        { required: true, message: "请填写合同金额（含税）", trigger: "blur" }
      ],
      currencyAmountNoTax: [
        { required: true, message: "请填写合同金额（不含税）", trigger: "blur" }
      ],
      durationCount: [
        { required: true, message: "请填写项目工期", trigger: "blur" }
      ],
      approvalTime: [
        { required: true, message: "请选择批准日期", trigger: "change" }
      ],
      effectiveDate: [
        { required: true, message: "请选择合同生效日期", trigger: "change" }
      ],
      signDate: [
        { required: true, message: "请选择合同签订日期", trigger: "change" }
      ],
      sectionStartRegionCode: [
        { required: true, message: "请选择发起单位", trigger: "change" }
      ],
      supplier: [
        { required: true, message: "请输入供应商/承包商", trigger: "change" }
      ],
      projectYear: [
        { required: true, message: "请选择项目年度", trigger: "change" }
      ],
      typeName: [
        { required: true, message: "请选择费用专项类型", trigger: "change" }
      ]
    };

    // 过滤工厂
    const filterText = ref("");
    watch(filterText, val => {
      treeRef.value?.filter(val);
    });
    const isNotProjectA = computed(() => projectInfo?.typeCode !== "A");
    const isDevice = computed(() => state.formData.sectionType === "2");

    //获取合同编号列表
    const getContractCode = async (query, key) => {
      if (!query) {
        contractList.value = [];
        return;
      }
      try {
        let params = {
          pageNum: 1,
          pageSize: 10
        };
        params[key] = query;
        const { code, data } = await getContractList(params);
        if (code === 200) {
          contractList.value = data.list;
        }
      } catch (err) {
        console.log(err);
      }
    };
    const getContractDocument = (item: any) => {
      proSecContractFileList({
        contractId: item.contractId,
        pageNum: 1,
        pageSize: 1000
      }).then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          const { list } = data;
          const arr = list.map((val: any) => {
            const item = JSON.parse(val.ext1);
            return {
              ...item,
              name: item.fileName
            };
          });
          defaultFileList.value = arr;
        }
      });
    };
    //切换合同
    const changeContract = async key => {
      let compareVal = key == "contractNo" ? "sectionCode" : "sectionName";
      const arr = contractList.value.filter(item => {
        return state.formData[compareVal] == item[key];
      });
      if (arr.length > 0) {
        state.contractInfo = arr[0];
        state.formData.sectionName = arr[0].contractName;
        state.formData.contractInfoId = arr[0].id;
        state.formData.contractId = arr[0].contractId;
        state.formData.sectionCode = arr[0].contractNo;
        // 合同金额（含税和不含税）
        state.formData.contractAmount = +arr[0].currencyAmount;
        state.formData.currencyAmountNoTax = +arr[0].currencyAmountNoTax;
        // 合同签订日期
        state.formData.signDate = arr[0].applyTime;
        show.value = true;
        // 查询合同文书
        getContractDocument(arr[0]);
      } else {
        state.formData.contractInfoId = "";
        state.formData.contractId = "";
        state.formData.contractAmount = undefined;
        state.formData.currencyAmountNoTax = undefined;
        defaultFileList.value = [];
        show.value = false;
      }
    };

    //获取项目组成员
    const getUserData = async (query = "") => {
      if (!query) {
        userList.value = [];
        return;
      }
      try {
        const params = {
          pageNum: 1,
          pageSize: 10,
          nameLike: query
        };
        const { code, data } = await getUserList(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return { value: item.id, label: `${item.name}(${item.userName})` };
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    const getContractBookList = () => {
      getContractBook({
        id: sectionId
      }).then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          defaultFileList.value = data.map((val: any) => {
            return {
              ...val,
              name: val.fileName
            };
          });
        }
      });
    };

    // 获取标段详情
    const getSectionDetail = async () => {
      try {
        const { code, data } = await getSectionInfo({ id: sectionId });
        if (code === 200) {
          // 根据合同id查询合同文书
          getContractBookList();
          state.formData = data || [];
          filterText.value = data.sectionStartFactoryName;
          state.formData.projectTmpId = +data.projectTmpId;
          state.formData.contractAmount = +data.contractAmount;
          templateId.value = data.projectTmpId;
          state.formData.leaderInfo = {
            value: +data?.leaderId,
            label: data?.leaderName
          };
          state.formData.typeName = {
            dicCode: data?.expensesTypeCode,
            dicValue: data?.expensesTypeName
          };
          userList.value = [state.formData.leaderInfo];
          if (data?.secEngineerList?.length) {
            const projectTypeModel = data.secEngineerList.filter(item => {
              return item.selectType === "S1";
            });
            state.formData.projectTypeModel = projectTypeModel.map(item => {
              return item.selectId;
            });
          }
          if (data.contractInfoId) {
            show.value = true;
            getContractDetail("");
          }
          nextTick(() => {
            proStageList.value = data?.proStageList?.length
              ? [...data.proStageList]
              : [];
          });
        }
      } catch (err) {
        console.log(err);
      }
    };

    //获取合同详细信息
    const getContractDetail = async type => {
      try {
        let json = {};
        if (sectionId) {
          json = { contractId: state.formData.contractId };
        } else if (type == "sectionCode" && state.formData.sectionCode) {
          json = {
            contractNo: state.formData.sectionCode
          };
        } else if (type == "sectionName" && state.formData.sectionName) {
          json = {
            contractName: state.formData.sectionName
          };
        } else {
          return;
        }
        const { code, data } = await importSectionCode(json);
        if (code === 200) {
          state.contractInfo = data;
          state.formData.contractInfoId = data.id;
          state.formData.contractId = data.contractId;
          state.formData.sectionCode = data.contractNo;
          state.formData.sectionName = data.contractName;
        }
        if (data) {
          show.value = true;
        } else {
          show.value = false;
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleSave = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formDataRef.value.validate(resolve)
        );
        if (!isValid) return;
        state.formData.leaderId = state.formData.leaderInfo.value;
        state.formData.leaderName = state.formData.leaderInfo.label;
        state.formData.expensesTypeCode = state.formData.typeName.dicCode;
        state.formData.expensesTypeName = state.formData.typeName.dicValue;
        if (show.value) {
          // 金额需要修改
          // state.formData.contractAmount = state.contractInfo.currencyAmount;
          // state.formData.currencyAmountNoTax = state.contractInfo.currencyAmountNoTax;
          state.formData.supplier = state.contractInfo.supplier;
        }
        if (state.formData.sectionType == 1) {
          //土建
          if (sectionId) {
            handleUpdate();
          } else {
            handleAdd();
          }
        } else if (state.formData.sectionType == 2) {
          editRef.value
            .save()
            .then(async data => {
              // 简化data中的参数
              let arr = [];
              data.forEach((item, index) => {
                let obj = {
                  index,
                  projectStageName: item.projectStageName
                } as any;
                let taskList = [];
                item.proTmpTaskList.forEach(task => {
                  let taskObj = {
                    approvalForm: task.approvalForm,
                    approvalNodeCode: task.approvalNodeCode,
                    approvalNodeName: task.approvalNodeName,
                    approvalNodeTmpAttachmentArr:
                      task.approvalNodeTmpAttachmentArr,
                    taskName: task.taskName
                  };
                  taskList.push(taskObj);
                });
                obj.proTmpTaskList = [...taskList];
                arr.push(obj);
              });
              if (sectionId) {
                handleUpdate(arr);
              } else {
                handleAdd(arr);
              }
            })
            .catch(err => {
              console.log("error", err);
              NotifMessage.warning(err);
            });
        } else {
          //服务
          if (sectionId) {
            handleUpdate();
          } else {
            handleAdd();
          }
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleDeptList = flag => {
      state.showDeptList = flag;
    };

    const handleAdd = async arr => {
      let params = Object.assign({}, state.formData, {
        newProjectTemplate: { proStageList: arr },
        documentAttachmentArr: defaultFileList.value.map((val: any) => {
          const arr = val.fileName.split(".");
          return {
            ...val,
            fileType: arr[arr.length - 1],
            bimInfo: null
          };
        })
      });
      const { code, message } = await addSection(params);
      if (code === 200) {
        clickEvent("项目标段", "保存", "新增项目标段");
        NotifMessage.success(message);
        goBack();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    const handleUpdate = async arr => {
      let params = Object.assign(
        {},
        state.formData,
        { id: sectionId },
        {
          newProjectTemplate: { proStageList: arr },
          documentAttachmentArr: defaultFileList.value.map((val: any) => {
            const arr = val.fileName.split(".");
            return {
              ...val,
              fileType: arr[arr.length - 1],
              bimInfo: null
            };
          })
        }
      );
      const { code, message } = await updateSection(params);
      if (code === 200) {
        clickEvent("项目标段", "保存", "编辑项目标段");
        NotifMessage.success(message);
        goBack();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    // 模板类型
    const initTemplateTypeList = async () => {
      try {
        const { data } = await projectTemplateList({
          isOriginal: "1",
          projectTemplateNameLike: "",
          projectTmpTypeCode: projectInfo?.typeCode,
          createUserNameLike: "",
          createTimeStrStart: "",
          createTimeStrEnd: "",
          pageNum: 1,
          pageSize: 0
        });
        templateList.value = data.list || [];
      } catch (err) {
        console.log(err);
      }
    };

    const getData = async templateId => {
      try {
        const { code, data } = await getTemplateInfo({ id: templateId });
        if (code === 200) {
          const { proStageList: proStageListData } = data;
          proStageList.value = [...proStageListData];
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleChangeTemp = id => {
      // 请求模板数据
      templateId.value = id;
      if (id) {
        getData(id);
      }
    };

    //修改标段类型
    const selectRadio = async val => {
      if (val == 1) {
        //土建
        state.formData.projectTmpId = null;
      } else if (val == 2) {
        //设备
        state.formData.projectTypeModel = [];
        state.formData.secEngineerList = [];
      }
      // if (val == 2) {
      //   // 设备没有合同签订日期
      //   state.formData.signDate = "";
      // } else {
      //   // 土建和服务没有合同生效日期
      //   state.formData.effectiveDate = "";
      // }
    };

    // 工程类型
    const getProjectBaseList = async () => {
      try {
        const { data } = await getBaseTree({
          pageNum: 1,
          pageSize: 0,
          belongType: 2
        });
        state.engineeringList = getTreeData(data) || [];
      } catch (err) {
        console.log(err);
      }
    };

    //过滤最后一级children为空数组数据
    const getTreeData = data => {
      for (var i = 0; i < data.length; i++) {
        if (data[i]?.children?.length) {
          // children若不为空数组，则继续 递归调用 本方法
          data[i].isLast = false;
          getTreeData(data[i].children);
        } else {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
          data[i].isLast = true; //判断是否最后一级
        }
      }
      return data;
    };

    //切换工厂单位
    const handleChangeDept = (node, nodeObj) => {
      let parent = nodeObj.isLeaf && nodeObj.level == 3 && nodeObj.parent.data;
      let data = nodeObj.data;
      state.formData.sectionStartRegionCode = parent.id;
      state.formData.sectionStartRegionName = parent.deptDescShrt;
      state.formData.sectionStartFactoryCode = data.id;
      state.formData.sectionStartFactoryName = data.deptDescShrt;
      if (nodeObj.isLeaf && nodeObj.level == 3) {
        state.showDeptList = false;
        filterText.value = data.deptDescShrt;
      }
    };

    // 调取工厂数据
    const getDeptTreeFunc = async () => {
      try {
        const { data } = await getDeptTree({});
        deptList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    getDeptTreeFunc();

    // 费用类型
    const initProjectTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_expenses_type" });
        expenseTypeList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    initProjectTypeList();

    const handleChange = () => {
      let secEngineerList = [];
      // const obj = proxy.$refs['cascader'].getCheckedNodes() //标签上定义的 ref值
      state.engineerTypeArray = [];
      state.ext1Array = [];
      state.fbTypeArray = [];
      state.zfbTypeArray = [];
      state.fxTypeArray = [];
      const obj = cascader.value.getCheckedNodes();
      const data = obj.filter(item => item?.data?.isLast);
      data.forEach(item => {
        state.engineerTypeArray.push(item.pathLabels[0]);
        state.ext1Array.push(item.pathLabels[1]);
        state.fbTypeArray.push(item.pathLabels[2]);
        state.zfbTypeArray.push(item.pathLabels[3]);
        state.fxTypeArray.push(item.pathLabels[4]);
        if (item?.pathNodes?.length) {
          item.pathNodes.forEach(obj => {
            secEngineerList.push({
              parentId: obj.data.parentId,
              selectId: obj.data.id,
              selectName: obj.data.itemText,
              selectType: obj.data.itemType,
              belongType: 2
            });
          });
        }
      });
      state.engineerTypeArray = unique(state.engineerTypeArray);
      state.ext1Array = unique(state.ext1Array);
      state.fbTypeArray = unique(state.fbTypeArray);
      state.zfbTypeArray = unique(state.zfbTypeArray);
      state.fxTypeArray = unique(state.fxTypeArray);
      let secEngineerListArray = uniqueObject(secEngineerList, "selectId");
      state.formData.secEngineerList = secEngineerListArray;
    };

    const unique = arr => {
      return Array.from(new Set(arr));
    };

    const uniqueObject = (arr, key) => {
      let set = [];
      let result = [];
      for (let val of arr) {
        if (!set.includes(val[key])) {
          result.push(val);
          set.push(val[key]);
        }
      }
      return result;
    };

    const goBack = () => {
      router.push(`/${props.menuType}/proManage/section`);
    };

    if (sectionId) {
      getSectionDetail();
    }
    getProjectBaseList();
    initTemplateTypeList();

    const uploadFielChange = (fileList: any) => {
      defaultFileList.value = fileList;
    };
    return {
      ...toRefs(state),
      formDataRef,
      userList,
      contractTypeList,
      rules,
      goBack,
      getUserData,
      getContractCode,
      handleSave,
      handleChange,
      cascader,
      show,
      editRef,
      isEdit,
      templateId,
      templateList,
      proStageList,
      handleChangeTemp,
      sectionId,
      selectRadio,
      getContractDetail,
      isSearching,
      handleDeptList,
      deptList,
      defaultFileList,
      uploadFielChange,
      filterNode,
      handleChangeDept,
      filterText,
      treeRef,
      expenseTypeList,
      contractList,
      changeContract,
      getContractDocument,
      projectInfo,
      isNotProjectA,
      isDevice
    };
  }
});
</script>

<style lang="scss" scoped>
:deep .el-input-number .el-input__inner {
  text-align: left;
}
.content-detail {
  position: absolute;
  bottom: 0;
  width: 100%;
}
.form-box {
  display: flex;
  flex-direction: column;
  :deep {
    .el-card__body {
      flex: 1;
      overflow: auto;
    }
  }
}

.content-box {
  height: 530px;
}

.form-h {
  height: calc(100% - 56px);
}

el-row {
  margin-left: 20px;
}

:deep .radio-item {
  .el-radio-button {
    width: 50%;

    .el-radio-button__inner {
      width: 100%;
    }
  }
}

.card-box-header {
  cursor: pointer;
}

.flex-item {
  display: flex;

  :deep .el-cascader {
    flex: 1;
  }

  .ml10 {
    margin-left: 10px;

    .red {
      color: red;
      margin-left: 2px;
      margin-right: 2px;
    }
  }
}

.filter-tree:deep {
  &.el-tree {
    position: absolute;
    top: 36px;
    width: 400px;
    max-height: 190px;
    overflow: auto;
    border: 1px solid #e4e8f2;
    z-index: 10;
  }
}

.label {
  padding-top: 15px;
  margin-left: 15px;
  font-size: 14px;
  line-height: 25px;
}

.value {
  padding-top: 15px;
  margin-left: 15px;
  font-size: 14px;
  color: rgb(174, 170, 170);
  line-height: 25px;
}
</style>
